package com.education.ai.util;

import com.education.ai.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 教师上下文工具类，用于获取当前登录教师信息
 */
@Component
public class TeacherContext {

    private static final Logger logger = LoggerFactory.getLogger(TeacherContext.class);
    
    private static AuthService authService;
    
    @Autowired
    public void setAuthService(AuthService authService) {
        TeacherContext.authService = authService;
    }
    
    /**
     * 获取当前登录教师ID
     *
     * @return 教师ID，如果未登录则返回null
     */
    public static String getCurrentTeacherId() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                logger.warn("无法获取请求上下文");
                return null;
            }
            
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                logger.debug("请求中未包含Authorization头信息");
                return null;
            }
            
            return authService.getUserIdFromToken(token);
        } catch (Exception e) {
            logger.error("获取当前教师ID失败: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 检查当前是否已登录
     *
     * @return 是否已登录
     */
    public static boolean isLoggedIn() {
        return getCurrentTeacherId() != null;
    }
} 